﻿using PlayListSet.Entity;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace PlayListSet
{
    /// <summary>
    /// UpdateSourceWindos.xaml 的交互逻辑
    /// </summary>
    public partial class UpdateSourceWindos : Window
    {
        public List<UpdateSourceModel> UpdateSourceModels {  get; set; }
        public UpdateSourceWindos(List<UpdateSourceModel> updateSourceModels )
        {
            InitializeComponent();
            UpdateSourceModels = updateSourceModels;
            foreach ( var model in UpdateSourceModels )
            {
                model.UserCommand.ExecuteEvent += (arg) => { 
                    var str = (string)arg;
                    if (str == "更新")
                    {
                        if (model.State == "正在更新")
                            return;
                        if (System.IO.File.Exists(model.SourceUrl))
                        {
                            if (model.State == "等待更新" || model.State == "连接失败")
                            {
                                Task.Factory.StartNew(() => {
                                    SendFile(model);
                                });
                               
                            }
                            else
                            {
                                model.Msg = model.State+",无法更新";
                            }
                        }
                        else
                        {
                            model.State = "资源不存在";
                            model.Msg = model.State + ",无法更新";
                        }
                       
                    }
                };
            }
            this.DataContext = this;
            Task.Factory.StartNew(() => { 
                for ( int i = 0; i < UpdateSourceModels.Count; i++ )
                {
                    if(UpdateSourceModels[i] != null )
                    {
                        var info = UpdateSourceModels[i];
                        if (System.IO.File.Exists(info.SourceUrl))
                        {
                            info.Size=new System.IO.FileInfo(info.SourceUrl).Length;
                        }
                        else
                        {
                            info.State = "资源不存在";
                        }
                    }
                }
            });
        }
       
       
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            button.IsEnabled = false;
            Task.Factory.StartNew(() => {
                try
                {
                    StartSend();
                  
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                button.Dispatcher.Invoke(() => { button.IsEnabled = true; }); 
            });
        }
        private void StartSend()
        {
            for ( int i = 0;i < UpdateSourceModels.Count;i++ ) 
            {
                if (UpdateSourceModels[i].State == "等待更新"|| UpdateSourceModels[i].State == "连接失败")
                {
                    SendFile(UpdateSourceModels[i]);
                }
            }
        }
        byte[] updateDate = Encoding.UTF8.GetBytes("updateDate");
        byte[] updateSource = Encoding.UTF8.GetBytes("updateSource");

        private void SendFile(UpdateSourceModel updateSourceModel)
        {
            updateSourceModel.State = "正在更新";
            TcpClient tcpClient = null;
            try
            {
                tcpClient = TcpTool.Connect(VCLib.Converts.IPConverts.ConverToIPEndPoint(updateSourceModel.ChannelInfo.IPEndPoint)
              , 2000);
            }
            catch (Exception ex)
            {
                updateSourceModel.State = "连接失败";
                updateSourceModel.Msg=ex.Message;
                return;
            }
            try
            {
                using (var stream = tcpClient.GetStream())
                {
                    byte[] result = new byte[1024];
               
                    if (updateSourceModel.IsData)
                    {
                        stream.Write(updateDate, 0, updateDate.Length);
                        Thread.Sleep(50);
                        var resState =  GetResState(stream);
                        Console.WriteLine("res 109:"+resState);
                        if (resState == 0xa1)
                        {
                            Console.WriteLine("send");

                            result = new byte[1024*4];
                            using(FileStream fs = new FileStream(updateSourceModel.SourceUrl, FileMode.Open, FileAccess.Read))
                            {
                                int len = 0;
                                while ((len = fs.Read(result, 0, result.Length)) > 0)
                                {
                                    updateSourceModel.CurrentSize += len;
                                    stream.Write(result, 0, len);
                                }
                                updateSourceModel.State = "更新完成";
                            }
                        }
                        else
                        {
                            throw new Exception("数据更新出错");
                        }
                    }
                    else
                    {
                        stream.Write(updateSource, 0, updateSource.Length);
                        Thread.Sleep(50);
                        var resState = GetResState(stream);

                        if (resState != 0xa1)//!=ok
                        {
                            throw new Exception("资源更新出错");
                        }
                        //发送文件名
                        string fileName = System.IO.Path.GetFileName(updateSourceModel.SourceUrl);
                        byte[] fileNameData = Encoding.UTF8.GetBytes(fileName);
                        stream.Write(fileNameData, 0, fileNameData.Length);
                        Thread.Sleep(50);
                        resState = GetResState(stream);

                        if (resState == 0xa1)
                        {
                            Thread.Sleep(50);
                            result = new byte[1024 * 4];
                            using (FileStream fs = new FileStream(updateSourceModel.SourceUrl, FileMode.Open, FileAccess.Read))
                            {
                                int len = 0;
                                while ((len = fs.Read(result, 0, result.Length)) > 0)
                                {
                                    updateSourceModel.CurrentSize += len;
                                    stream.Write(result, 0, len);
                                }
                                updateSourceModel.State = "更新完成";
                            }
                            return;
                        }
                        else if(resState == 0xa3)
                        {
                            updateSourceModel.State = "资源已存在";
                        }
                    }

                }
            }
            catch (Exception)
            {

                throw;
            }

        }
        private byte GetResState(NetworkStream networkStream)
        {
            byte[] result = new byte[1024];
            int num = networkStream.Read(result, 0, result.Length); //将数据读到result中      
            if (num == 1 )
            {
                return result[0];
            }
            return 0x00;
        }
    }
}
